package stream;
import method_references.Employee;
import method_references.EmployeeData;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author mubei
 * @date 2021/11/24
 * @description  测试中间操作
 */
public class StreamAPITest1 {



    @Test()
    public void test1() {
        List<Employee> list = EmployeeData.getAllEmployees();
        Stream<Employee> stream = list.stream();
        // 查询员工表中  大于8999的
        stream.filter(e->e.getSalary()>8999).forEach(System.out::println);

        System.out.println("跳过数据");
        // forEach 就会终止stream
        stream = list.stream();
        stream.skip(2).forEach(System.out::println);

        System.out.println("前n个");
        list.stream().limit(2).forEach(System.out::println);

        // 数据去重
        System.out.println("数据去重");
        list.stream().distinct().forEach(System.out::println);

    }


    /*
    * 映射  转化
    * */
    @Test()
    public void test2() {
        // map 将元素转换成其他形式或提取信息
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(str->str.toUpperCase()).forEach(System.out::println);

        List<Employee> list1 = EmployeeData.getAllEmployees();
        // 获得员工姓名长度大于3的员工的姓名
        list1.stream().map(Employee::getName).filter(name -> name.length() >(2)).forEach(System.out::println);

        //flatMap  接受一个函数作为参数  将流中的每个值转化成另一个流
        // add  和  addAll的区别   将一个流打散
        //练习2      流中包含流
        Stream<Stream<Character>> stream = list.stream().map(StreamAPITest1::fromStringToStream);
        stream.forEach(s->{
            s.forEach(System.out::println);
        });
        System.out.println("flatMap");
        list.stream().flatMap(StreamAPITest1::fromStringToStream).forEach(System.out::println);
    }


    @Test()
    public void test3() {
         List<Integer> list1 = Arrays.asList(1,2,3);
         List<Integer> list2 = Arrays.asList(4,5,6);

         list1.addAll(list2);
    }

    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character>list = new ArrayList<>();

        for (char c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }



    /*
    * 排序
    * */
    @Test()
    public void test4() {
        // sorted() 自然排序
        List<Integer> list  = Arrays.asList(1,6,4);
        list.stream().sorted().forEach(System.out::println);

        List<Employee> allEmployees = EmployeeData.getAllEmployees();

        //抛异常  没有事先comparable接口
        //allEmployees.stream().sorted().forEach(System.out::println);
        allEmployees.stream().sorted((e1,e2)->Integer.compare(e2.getId(),e1.getId())).forEach(System.out::println);

    }
}
